'use client';

import { formatCurrency, staticGo } from '@/utils/common';
import Image from 'next/image';
import { useEffect, useRef, useState } from 'react';
import CustomPagination from '../CustomPagination';
import NoProductsFound from './NoProductsFound';
import NoSearchResults from './NoSearchResults';
import Link from 'next/link';
import { useActions, useGlobalState } from '@/hooks';
import { showToast } from '@/components/Toast';
import './ProductList.scss';
import StockStatus from '@/views/Product/components/StockStatus';

const ProductItem = ({
  sku,
  isLogin,
  onClickAddToMySku,
  onClickAddToCompare,
}: {
  sku: Obj;
  isLogin: boolean;
  onClickAddToMySku: Fn;
  onClickAddToCompare: Fn;
}) => {
  // const [inMySkuList, setInMySkuList] = useState(false);
  // const toogleInMySkuList = () => {
  //   setInMySkuList((flag: any) => !flag);
  // };
  const [loginURL, setLoginURL] = useState('');
  const [imgUrl, setImgUrl] = useState(sku?.gallery?.at(0) || '');
  const [discountOff, setDiscountOff] = useState<any>('');

  const getLoginURL = () => {
    const url =
      process.env.NEXT_PUBLIC_LOGIN_URL +
      '?return_url=' +
      encodeURIComponent(
        location.origin + '/api/login?backurl=' + window.location.href
      );

    return url;
  };

  useEffect(() => {
    setImgUrl(sku?.gallery?.at(0) || '');
    const disc = sku?.special_price
      ? Number((100 * (sku.price - sku.special_price)) / sku.price).toFixed(0)
      : '';
    setDiscountOff(disc);
    setLoginURL(getLoginURL());
  }, [sku]);

  return (
    <div className="product-list-item">
      {isLogin ? (
        <Link
          className="product-list-item-image-link"
          href={`/product/${sku.sku}`}
        >
          <div className="product-list-item-image-wrapper">
            <Image
              fill={true}
              sizes={'100%'}
              priority={false}
              src={imgUrl}
              alt={''}
              className="product-list-item-image"
            />
            {sku.freeshipping == '1' && (
              <div className="product-list-item-free">free au shipping</div>
            )}
          </div>
        </Link>
      ) : (
        <div className="product-list-item-image-wrapper">
          <Image
            fill={true}
            sizes={'190px'}
            priority={false}
            src={imgUrl}
            alt={''}
            className="product-list-item-image"
          />
          {sku.freeshipping == '1' && (
            <div className="product-list-item-free">free au shipping</div>
          )}
        </div>
      )}

      {isLogin ? (
        <div className="product-list-item-infos">
          <div className="product-list-item-mysku">
            <button
              className="product-list-item-button-add"
              onClick={onClickAddToMySku}
              data-eid={sku.entity_id}
              data-sku={sku.sku}
            >
              {sku.my_sku ? (
                <span className="iconfont icon-check-fill" />
              ) : (
                <span className="iconfont icon-check-line" />
              )}
              Add to My SKU List
            </button>
          </div>
          {sku.special_price ? (
            <div className="product-list-item-priceinfo">
              <div className="product-list-item-price">
                {/* <span className="price-label">From</span> */}
                {formatCurrency(sku.special_price)}
                <span className="price-discount">{discountOff}% off</span>
              </div>
              <div className="product-list-item-row">
                <div className="product-list-item-regular">
                  <span className="price-label">Regular: </span>
                  {formatCurrency(sku.price)}
                </div>
                <div className="product-list-item-rrp">
                  {sku.RrpPrice && (
                    <>
                      <span className="price-label">RRP: </span>
                      {formatCurrency(sku.RrpPrice)}
                    </>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="product-list-item-priceinfo">
              <div className="product-list-item-price">
                {formatCurrency(sku.price)}
              </div>
              <div className="product-list-item-rrp">
                {sku.RrpPrice && <>RRP: {formatCurrency(sku.RrpPrice)}</>}
              </div>
            </div>
          )}
          <div className="product-list-item-title text-overflow-2">
            <Link href={`/product/${sku.sku}`}>{sku.title}</Link>
          </div>
          <div className="product-list-item-sku text-overflow-1">
            SKU: {sku.sku}
          </div>
          <div className="product-list-item-actions">
            {!(sku?.spec?.length > 0) && (
              <>
                <StockStatus
                  in_stock={sku?.in_stock}
                  stock_qty={sku?.stock_qty}
                  status={sku?.status}
                  onlyIcon={true}
                />
                <div className="product-list-item-compare">
                  {sku.in_compare ? (
                    <div className="product-list-item-button-compare in-compare-list">
                      In Compare List
                    </div>
                  ) : (
                    <button
                      className="product-list-item-button-compare"
                      onClick={() => onClickAddToCompare(sku)}
                      data-eid={sku.entity_id}
                      data-sku={sku.sku}
                    >
                      Add to Compare
                    </button>
                  )}
                </div>
              </>
            )}
          </div>
        </div>
      ) : (
        <div className="product-list-item-infos">
          <div className="product-list-item-title text-overflow-2">
            {sku.title}
          </div>
          <div className="product-list-item-tologin">
            <Link href={loginURL}>Login for More Details</Link>
          </div>
        </div>
      )}
    </div>
  );
};

/* ==========================================================================================================
          ProductList Component
========================================================================================================== */

const ProductList = ({
  basePath,
  products,
  onGoPage,
  onChangePageSize,
  isLoading,
  isLogin,
  onSelectChange,
}: {
  basePath: string;
  products: Obj;
  onGoPage: Fn;
  onChangePageSize: Fn;
  isLoading: boolean;
  isLogin: boolean;
  onSelectChange: Fn;
}) => {
  const { result, current_page, total_pages, page_size, total } = products;

  const [skuList, setSkuList] = useState<any>(result);

  const { compareList } = useGlobalState('product');
  const { addCompareList } = useActions();

  const handleAddToMySku = (e: any) => {
    const cData = e?.currentTarget?.dataset || {};
    console.log('handleAddToMySku', cData);
    const newList = [...skuList];
    const sku = newList.find(s => s.entity_id == cData.eid);
    if (sku) {
      sku.my_sku = !sku.my_sku;
      setSkuList(newList);
      onSelectChange && onSelectChange(newList);
    }
  };
  const handleAddToCompare = (e: any) => {
    const cData = { title: e.title, sku: e.sku, image: e.gallery?.at(0) };
    console.log('handleAddToCompare', cData);
    addCompareList(cData);
  };

  const handlePagination = (newPage: any) => {
    console.log('page::', newPage);
    onGoPage && onGoPage(newPage);
  };

  const initData = async (sourceList?: any[]) => {
    if (result?.length > 0) {
      const list = [...result];
      const inListSkus = compareList.map(p => p.sku);
      list.forEach((p: any) => {
        if (inListSkus.includes(p.sku)) p.in_compare = true;
        else p.in_compare = false;
      });
      setSkuList(list);
    } else {
      setSkuList([]);
    }
  };
  const initDataRef = useRef(initData);
  initDataRef.current = initData;

  useEffect(() => {
    // if (!result) return;
    // console.log('-----------init data');
    result && compareList && initDataRef.current();
  }, [result, compareList]);

  return (
    <div
      className={
        'product-list' + (isLoading && !skuList?.length ? ' isLoading' : '')
      }
    >
      {skuList?.length == 0 ? (
        basePath == 'catalogsearch' ? (
          <NoSearchResults />
        ) : (
          <NoProductsFound />
        )
      ) : (
        <>
          <div className="product-list-wrapper">
            {(skuList || [])?.map((sku: any, index: number) => (
              <ProductItem
                key={index + '_' + sku.sku}
                sku={sku}
                isLogin={isLogin}
                onClickAddToMySku={handleAddToMySku}
                onClickAddToCompare={handleAddToCompare}
              />
            ))}
          </div>
          <div className="product-list-pagination">
            <CustomPagination
              count={total_pages}
              page={current_page}
              pageSize={page_size}
              onChange={handlePagination}
              onChangePageSize={onChangePageSize}
            />
          </div>
        </>
      )}
    </div>
  );
};

export default ProductList;
